package util;


import android.content.Context;
import android.util.Log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 创建日期：18-9-8 下午12:24
 * @author machong
 * @company
 * 文件名称： LogUtil.java
 * 类说明： 带日志文件输入,可控制开关
 */

public class LogUtil {

    public static Boolean LogUtil_SWITCH = true; // 日志文件总开关
    public static Boolean LogUtil_WRITE_TO_FILE = false; // 日志写入文件开关
    private static char LogUtil_TYPE = 'v'; // 输入日志类型，w代表只输出告警信息等，v代表输出所有信息
    private static String LogUtil_PATH_SDCARD_DIR = "tskj_log"; //日志文件在sdcard中的路径
    private static int SDCARD_LOG_FILE_SAVE_DAYS = 0; // sd卡中日志文件的最多保存天数
    private static String LogFileName = "LogUtil.txt"; //本类输出的日志文件名称
    private static SimpleDateFormat logUtilSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 日志的输出格式
    private static SimpleDateFormat logfile = new SimpleDateFormat("yyyy-MM-dd"); // 日志文件格式
    private static String LOG_FLAG = " tutu ";

    public Context context;

    public static void w(String tag, Object msg) { // 警告信息
        log(tag, msg.toString(), 'w');
    }

    public static void e(String tag, Object msg) { // 错误信息
        log(tag, msg.toString(), 'e');
    }

    public static void d(String tag, Object msg) {// 调试信息
        log(tag, msg.toString(), 'd');
    }

    public static void i(String tag, Object msg) {
        log(tag, msg.toString(), 'i');
    }

    public static void v(String tag, Object msg) {
        log(tag, msg.toString(), 'v');
    }

    public static void w(String tag, String text) {
        log(tag, LOG_FLAG + text, 'w');
    }

    public static void e(String tag, String text) {
        log(tag, LOG_FLAG + text, 'e');
    }

    public static void d(String tag, String text) {
        log(tag, LOG_FLAG + text, 'd');
    }

    public static void i(String tag, String text) {
        log(tag, LOG_FLAG +text, 'i');
    }

    public static void v(String tag, String text) {
        log(tag, LOG_FLAG + text, 'v');
    }


    /**
     * 根据tag, msg和等级，输出日志
     * @param tag
     * @param msg
     * @param level
     */
    private static void log(String tag, String msg, char level) {
        if (LogUtil_SWITCH) {
            if ('e' == level && ('e' == LogUtil_TYPE || 'v' == LogUtil_TYPE)) { // 输出错误信息
                Log.e(tag, msg);
            } else if ('w' == level && ('w' == LogUtil_TYPE || 'v' == LogUtil_TYPE)) {
                Log.w(tag, msg);
            } else if ('d' == level && ('d' == LogUtil_TYPE || 'v' == LogUtil_TYPE)) {
                Log.d(tag, msg);
            } else if ('i' == level && ('d' == LogUtil_TYPE || 'v' == LogUtil_TYPE)) {
                Log.i(tag, msg);
            } else {
                Log.v(tag, msg);
            }
            if (LogUtil_WRITE_TO_FILE)
                writeLogtoFile(String.valueOf(level), tag, msg);
        }
    }


    private static String getLogPath() {
        String path = "";
        // 获取扩展SD卡设备路径
        String sDStateString = android.os.Environment.getExternalStorageState();

        // 拥有可读可写权限
        if (sDStateString.equals(android.os.Environment.MEDIA_MOUNTED)) {
            // 获取扩展存储设备的文件目录
            File SDFile = android.os.Environment.getExternalStorageDirectory();
            path = SDFile.getAbsolutePath() + File.separator + LogUtil_PATH_SDCARD_DIR;
        }
        return path;

    }

    /**
     * 打开日志文件并写入日志
     * @param mylogtype
     * @param tag
     * @param text
     */
    private static void writeLogtoFile(String mylogtype, String tag, String text) {
        Date nowtime = new Date();
        String needWriteFiel = logfile.format(nowtime);
        String needWriteMessage = logUtilSdf.format(nowtime) + "    " + mylogtype + "    " + tag + "    " + text;

        // 取得日志存放目录
        String path = getLogPath();
        if (path != null && !"".equals(path)) {
            try {
                // 创建目录
                File dir = new File(path);
                if (!dir.exists())
                    dir.mkdir();
                // 打开文件
                File file = new File(path + File.separator + needWriteFiel + LogFileName);
                if(!file.exists()){
                    boolean b_ret = file.createNewFile();
                    if(!b_ret)
                        return;
                }
                FileWriter filerWriter = new FileWriter(file, true);// 后面这个参数代表是不是要接上文件中原来的数据，不进行覆盖
                BufferedWriter bufWriter = new BufferedWriter(filerWriter);
                bufWriter.write(needWriteMessage);
                bufWriter.newLine();
                bufWriter.close();
                filerWriter.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    /**
     * 删除日志文件
     */
    public static void delFile() {
        // 取得日志存放目录
        String path = getLogPath();
        if (path != null && !"".equals(path)) {
            String needDelFile = logfile.format(getDateBefore());
            File file = new File(path, needDelFile + LogFileName);
            if (file.exists()) {
                file.delete();
            }
        }
    }

    /**
     *得到现在时间前的几天日期，用来得到需要删除的日志文件
     * @return
     */
    private static Date getDateBefore() {
        Date nowtime = new Date();
        Calendar now = Calendar.getInstance();
        now.setTime(nowtime);
        now.set(Calendar.DATE, now.get(Calendar.DATE) - SDCARD_LOG_FILE_SAVE_DAYS);
        return now.getTime();
    }

}
